package com.loto.webapp.action.ctrl;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import com.loto.webapp.common.BaseAction;
import com.loto.webapp.model.TopMenu;
import com.loto.webapp.util.Files;

public class TopMenuAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3237990190557246490L;

	private List<TopMenu> menuList;

	private List<TopMenu> childMenuList;

	private String currentParentId;

	private String currentId;

	public String execute() {
		String userName = getLoginUsername();
		if (userName.equals(null) || userName.equals("")) {
			return ERROR;
		}
		return loadMenu(userName);
	}

	private String loadMenu(String username) {
		try {
			Document document = Files.getMenuXml(
					ServletActionContext.getRequest(), username);
			org.w3c.dom.Element rootElement = document.getDocumentElement();
			NodeList list = rootElement.getElementsByTagName("Menu");
			this.menuList = new ArrayList<TopMenu>();
			boolean hasRight = false;
			for (int i = 0; i < list.getLength(); i++) {
				org.w3c.dom.Element element = (org.w3c.dom.Element) list
						.item(i);
				TopMenu menu = new TopMenu();
				menu.setId(element.getAttribute("ID"));
				menu.setName(element.getAttribute("Name"));
				menu.setLink(element.getAttribute("Url"));
				menuList.add(menu);
				if (element.getAttribute("ID").equals(currentParentId)) {
					this.childMenuList = new ArrayList<TopMenu>();
					NodeList sublist = element
							.getElementsByTagName("ChildMenu");
					for (int j = 0; j < sublist.getLength(); j++) {
						org.w3c.dom.Element subelement = (org.w3c.dom.Element) sublist
								.item(j);
						TopMenu childMenu = new TopMenu();
						childMenu.setId(subelement.getAttribute("ID"));
						childMenu.setName(subelement.getAttribute("Name"));
						childMenu.setLink(subelement.getAttribute("Url"));
						childMenuList.add(childMenu);
						if (subelement.getAttribute("ID").equals(currentId)) {
							hasRight = true;
						}
					}
				}
			}
			if (!hasRight)
				return ERROR;
			return SUCCESS;
		} catch (Exception e) {
			return ERROR;
		}
	}

	public List<TopMenu> getMenuList() {
		return menuList;
	}

	public void setMenuList(List<TopMenu> menuList) {
		this.menuList = menuList;
	}

	public String getCurrentParentId() {
		return currentParentId;
	}

	public void setCurrentParentId(String currentParentId) {
		this.currentParentId = currentParentId;
	}

	public String getCurrentId() {
		return currentId;
	}

	public void setCurrentId(String currentId) {
		this.currentId = currentId;
	}

	public List<TopMenu> getChildMenuList() {
		return childMenuList;
	}

	public void setChildMenuList(List<TopMenu> childMenuList) {
		this.childMenuList = childMenuList;
	}
}
